import React, { Component } from "react";
import { connect } from "react-redux";
import { Form, Switch, Checkbox, Input, Radio, InputNumber, Button, message } from "antd";
import Priority from "components/template/priority";
import { messages } from "share/common";
import Remind from "components/template/remind/remind";
import WrapFormItem from "components/wrap-form-item";
import Chooser from "components/chooser";
import beepTimerService from "../beep-timer.service";
import CompactInput from "components/compact-input";

@Form.create()
@connect(mapStateToProps)
class CorporateContent extends Component {
  state = {
    priority: {},
    saveLoading: false,
  };

  targetOptions = [
    {
      label: messages("basic-13.key308") /*合同申请人*/,
      value: "APPLICANT",
    },
    {
      label: messages("basic-13.key309") /*合同经办人*/,
      value: "EMPLOYEE",
    },
    {
      label: messages("basic-13.key170") /*申请人部门经理*/,
      value: "APPLICANT_MANAGER",
    },
    {
      label: messages("basic-13.key310") /*经办人部门经理*/,
      value: "EMPLOYEE_MANAGER",
    },
  ];

  options = [
    { label: messages("basic-13.key8") /*启用temp*/, value: true },
    { label: messages("basic-13.key227") /*不启用*/, value: false },
  ];

  componentWillMount() {
    const { info, record } = this.props.params,
      { company } = this.props;
    let priority = info.id
      ? {
          companyOID: record.companyOID,
          levelOrgName: record.levelOrgName,
          levelOrgId: record.levelOrgId,
          levelCode: record.levelCode,
        }
      : {
          levelOrgName: company.setOfBooksName,
          levelOrgId: company.setOfBooksId,
          levelCode: "SET_OF_BOOK",
        };
    this.setState({ priority });
  }

  handlePriority = (value) => {
    let _value = value || {};
    const { info } = this.props.params;
    const { priority } = this.state;
    if (!info.id && priority.levelOrgId !== _value.levelOrgId) {
      this.props.form.setFieldsValue({ warpObject: [] });
    }
    this.setState({ priority: _value });
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { priority } = this.state,
          { info } = this.props.params,
          { close } = this.props;
        if (!priority.levelOrgId) {
          message.error(messages("basic-13.key220") /*请选择所属组织*/);
          return -1;
        }
        if (!value.warpTime.differenceDate) {
          message.error(messages("basic-13.key226") /*请输入触发时间*/);
          return -1;
        }
        this.setState({ saveLoading: true });
        this.warpRemind
          .saveValue()
          .then((id) => {
            let params = {
              enabledFlag: value.enabledFlag,
              code: "ContractPaymentTask",
              hour: Number(this.warpRemind.getValue().remindWarpValue.remindTimes[0].split(":")[0]),
              ...priority,
            };
            params.params = Object.assign(
              {
                title: value.title,
                content: value.content,
                paymentRemindPersonTypes: value.paymentRemindPersonTypes,
                regulationId: id,
                needBillContent: value.needBillContent,
                warpObject: value.warpObject,
                ...priority,
              },
              value.warpTime
            );
            params.params = JSON.stringify(params.params);
            info.id && (params.id = info.id);
            beepTimerService.newBeepTimer(params).then(() => {
              this.setState({ saveLoading: false });
              close(true);
            });
          })
          .catch((e) => {
            this.setState({ saveLoading: false });
            e.response && message.error(e.response.data.message);
          });
      }
    });
  };

  render() {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const { close } = this.props;
    const { info, record } = this.props.params;
    const { priority, saveLoading } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
    };
    return (
      <div>
        <Form className={"new-form"}>
          <Form.Item label={messages("common.column.status") /*状态*/} {...formItemLayout}>
            {getFieldDecorator("enabledFlag", {
              rules: [{ required: true }],
              valuePropName: "checked",
              initialValue: info.hasOwnProperty("enabledFlag") ? info.enabledFlag : true,
            })(<Switch />)}
          </Form.Item>
          <Priority
            required
            top="SET_OF_BOOK"
            defaultValue={priority}
            onChange={this.handlePriority}
            showCompanyComponent={false}
            formItemLayout={formItemLayout}
            disabled={!!info.id}
            needSetOfBooksId
          />
          <h3 className="sub-title">{messages("basic-13.key12") /*提醒对象*/}</h3>
          <Form.Item label={messages("basic-13.key12") /*提醒对象*/} {...formItemLayout}>
            {getFieldDecorator("paymentRemindPersonTypes", {
              rules: [
                {
                  required: true,
                  message: messages("basic-13.key311") /*提醒对象为必填*/,
                },
              ],
              initialValue: record.paymentRemindPersonTypes || ["APPLICANT"],
            })(<Checkbox.Group options={this.targetOptions} />)}
          </Form.Item>
          <h3 className="sub-title">{messages("basic-13.key15") /*消息内容*/}</h3>
          <Form.Item label={messages("basic-13.key16") /*消息标题*/} {...formItemLayout}>
            {getFieldDecorator("title", {
              rules: [
                {
                  required: true,
                  message: messages("common.can.not.be.empty", {
                    arg1: messages("basic-13.key16") /*消息标题*/,
                  }) /*{arg1} 不能为空*/,
                },
                {
                  max: 50,
                  message: messages("common.max.characters.length", {
                    arg1: 50,
                  }) /*最多输入{arg1}个字符*/,
                },
              ],
              initialValue: record.title,
            })(<Input placeholder={messages("basic-13.key307") /*合同付款提醒*/} />)}
          </Form.Item>
          <Form.Item label={messages("basic-13.key17") /*消息正文*/} {...formItemLayout}>
            {getFieldDecorator("content", {
              rules: [
                {
                  required: true,
                  message: messages("common.can.not.be.empty", {
                    arg1: messages("basic-13.key17") /*消息正文*/,
                  }) /*{arg1} 不能为空*/,
                },
                {
                  max: 100,
                  message: messages("common.max.characters.length", {
                    arg1: 100,
                  }) /*最多输入{arg1}个字符*/,
                },
              ],
              initialValue: record.content,
            })(<Input.TextArea placeholder={messages("basic-13.key312") /*请及时付款*/} />)}
          </Form.Item>
          <Form.Item label={messages("basic-13.key313") /*合同行详情*/} {...formItemLayout}>
            {getFieldDecorator("needBillContent", {
              rules: [{ required: true }],
              initialValue: record.hasOwnProperty("needBillContent") ? record.needBillContent : false,
            })(<Radio.Group options={this.options} />)}
          </Form.Item>
          <h3 className="sub-title">{messages("basic-13.key18") /*消息触发*/}</h3>
          <Form.Item label={messages("basic-13.key231") /*触发对象*/} {...formItemLayout}>
            {getFieldDecorator("warpObject", {
              rules: [
                {
                  required: true,
                  message: messages("common.can.not.be.empty", {
                    arg1: messages("basic-13.key231") /*触发对象*/,
                  }) /*{arg1} 不能为空*/,
                },
              ],
              initialValue: record.warpObject,
            })(
              <WrapFormItem>
                {() => (
                  <CompactInput>
                    <Input value={messages("finance-6.key79") /*合同类型*/} disabled />
                    <Chooser
                      placeholder={messages("basic-13.key232") /*默认全部，请选择*/}
                      type="notification_contract_type"
                      labelKey="contractTypeName"
                      valueKey="id"
                      value={getFieldValue("warpObject")}
                      listExtraParams={{
                        setOfBooksId: priority.levelCode === "COMPANY" ? priority.setOfBooksId : priority.levelOrgId,
                      }}
                      onChange={(value) => setFieldsValue({ warpObject: value })}
                    />
                  </CompactInput>
                )}
              </WrapFormItem>
            )}
          </Form.Item>
          <Remind id={record.regulationId} onRef={(ref) => (this.warpRemind = ref)} hideType>
            <Form.Item label={messages("basic-13.key233") /*触发时间*/} {...formItemLayout}>
              {getFieldDecorator("warpTime", {
                rules: [
                  {
                    required: true,
                    message: messages("common.can.not.be.empty", {
                      arg1: messages("basic-13.key233") /*触发时间*/,
                    }) /*{arg1} 不能为空*/,
                  },
                ],
                initialValue: info.hasOwnProperty("id")
                  ? {
                      differenceDate: record.differenceDate,
                    }
                  : {},
              })(
                <WrapFormItem>
                  {(onChange, value) => (
                    <div>
                      {messages("basic-13.key314") /*计划付款日期前*/}
                      <InputNumber
                        precision={0}
                        min={0}
                        step={1}
                        value={value.differenceDate}
                        onChange={(day) => onChange({ differenceDate: day })}
                      />
                      {messages("basic-13.key236") /*天需要提醒员工*/}
                    </div>
                  )}
                </WrapFormItem>
              )}
            </Form.Item>
          </Remind>
        </Form>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={saveLoading}>
            {messages("common.ok") /*确定*/}
          </Button>
          <Button onClick={() => close()}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
  };
}

export default CorporateContent;
